<?php
class Application_Model_Galeria extends Zend_Db_Table_Abstract{
    protected $_name = 'galerias';

    protected $_dependentTables = array('Foto');

    public function getById($id){
        $select = $this->select()
            ->where("status = 'A' AND id = ?", $id);

        $result = $this->fetchAll($select);
        $arrGaleria = $result->toArray();

        $fotosObj = new Application_Model_Foto();
        $fotos = $fotosObj->getByGaleria($arrGaleria[0]['id']);

        $arrGaleria[0]['Fotos'] = array();

        array_push($arrGaleria[0]['Fotos'], $fotos);

        return $arrGaleria;
    }

    public function getGalerias(){
        $select = $this->select()
            ->where(" status = 'A' AND fecha <= Now()")
            ->order(array("fecha DESC", "id DESC"));

        $result = $this->fetchAll($select);
        $arrGalerias = $result->toArray();
        $allGalerias = array();

        foreach ($arrGalerias as $g) {
            $fotosObj = new Application_Model_Foto();
            $fotos = $fotosObj->getByGaleria($g['id']);

            $g['Fotos'] = array();

            array_push($g['Fotos'], $fotos);
            array_push($allGalerias, $g);
        }

        return $allGalerias;
    }
	
	public function getGaleriasLimit($limit = 4){
        $select = $this->select()
            ->where(" status = 'A' AND fecha <= Now()")
            ->order(array("fecha DESC", "id DESC"))
			->limit($limit);

        $result = $this->fetchAll($select);
        $arrGalerias = $result->toArray();
        $allGalerias = array();

        foreach ($arrGalerias as $g) {
            $fotosObj = new Application_Model_Foto();
            $fotos = $fotosObj->getByGaleria($g['id']);

            $g['Fotos'] = array();

            array_push($g['Fotos'], $fotos);
            array_push($allGalerias, $g);
        }

        return $allGalerias;
    }

    public function addGaleria($titulo, $fecha, $status){
        $row = $this->createRow();
        $row->titulo = $titulo;
        $row->fecha = $fecha;
        $row->status = $status;

        $row->save();

        $id = $this->_db->lastInsertId();

        return $id;
    }

    public function updateGaleria($titulo, $id){
        $row = $this->find($id)->current();

        $row->titulo = $titulo;

        if($row->save()){
            return true;
        }else{
            return false;
        }
    }
}